// ==UserScript==
// @name         Automatizaciones Integra
// @namespace    http://tampermonkey.net/
// @version      1.5
// @description
// @include      *://portalitss.meyss.es/*
// ==/UserScript==

/* CHANGELOG

1.5: Cambio de definicion de hotkeys
     Organizacion del codigo e implementacion de bloques plegables

*/

(function() {

    let currentElement = "";

    //////////////////////////////////////////////////////////
    //
    //          INICIO
    //    Definicion de hotkeys
    //
    /*//////////////////////////////////////////////////////*/ {

    const scriptHotkeys = document.createElement('script');
    scriptHotkeys.src = 'https://cdnjs.cloudflare.com/ajax/libs/mousetrap/1.6.5/mousetrap.min.js';
    scriptHotkeys.onload = function() {
		const pluginGlobalBind = document.createElement('script');
		pluginGlobalBind.src = 'https://cdnjs.cloudflare.com/ajax/libs/mousetrap/1.6.5/plugins/global-bind/mousetrap-global-bind.min.js';
		pluginGlobalBind.onload = function() {

            /* FUNCIONES AUXILIARES */ {

            function getElementByXPath(path) {
				return new XPathEvaluator()
					.createExpression(path)
					.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)
					.singleNodeValue;
			}

			function sleep(time) {
				return new Promise((resolve) => setTimeout(resolve, time));
			}

			async function waitForElement(xpath) {
				do {
					currentElement = getElementByXPath(xpath);
					await sleep(20);
				} while (!currentElement);
			}

			function ifEnterPress(campo) {
				if (window.event && window.event.keyCode == 13) {
					currentElement = document.getElementById('formulario:j_idt960:guardar:control-guardar');
					console.log("sdfdsfdsd");
					currentElement.click();
				}
			}
            /* FIN FUNCIONES AUXILIARES */ }

			let currentHotkey = localStorage.getItem("CurrentHotkey");
			console.log("CurrentHotkey: " + currentHotkey);

            /* HOTKEY 1 ARCHIVO */ {
			Mousetrap.bindGlobal('alt+a', async function(e) {
				e.preventDefault(); // Prevent default behavior of hotkey

				currentElement = document.getElementById('formulario:barraPestannas:pesAnotaciones:pestanna-pesAnotaciones');
				localStorage.setItem("CurrentHotkey", "HK1STAGE1");
				currentElement.click();
			});
			if (currentHotkey == "HK1STAGE1") {
				let currentElement = document.getElementById('formulario:linkCambiaModoEdicion');
				if (currentElement) {
					localStorage.setItem("CurrentHotkey", "HK1STAGE2");
					currentElement.click();
				} else {
					console.log('Element not found linkCambiaModoEdicion');
				}
			}
			if (currentHotkey == "HK1STAGE2") {
				let currentElement = document.getElementById('formulario:transferidoCheck');
				if (currentElement) {
					if (!currentElement.checked) {
						currentElement.click();
					}
					currentElement = document.getElementById('formulario:guardarArchivo');
					currentElement.click();
					localStorage.setItem("CurrentHotkey", "");

				} else {
					console.log('Element not found transferidoCheck');
				}
			}
			/* FIN HOTKEY 1 ARCHIVO */ }

			/* HOTKEY 2 VISAR O FINALIZAR */ {
			Mousetrap.bindGlobal('alt+f', async function(e) {
				e.preventDefault(); // Prevent default behavior of hotkey

				currentElement = document.getElementById('formulario:j_idt960:editarOrd:control-editarOrd');
				currentElement.click();
				await waitForElement('//*[@id="formulario:j_idt960:guardar:control-guardar"]');

				currentElement = document.getElementById('formulario:listaEstados_focus');
				if (currentElement) {
					currentElement.focus();
					currentElement = document.getElementById('formulario:listaEstados_input');
					if (currentElement.options[currentElement.selectedIndex].text == "Actuaciones Concluidas") {
						let optionLabels = Array.from(currentElement.options).map((opt) => opt.text);
						if (optionLabels.includes("Visado")) {
							currentElement.value = "12"; // Seleccionar Visado
							currentElement.dispatchEvent(new Event('change'));
							await waitForElement('//*[@id="formulario:labelVisador:selectVisador_focus"]');
							currentElement = document.getElementById('formulario:labelVisador:selectVisador_focus');
							currentElement.addEventListener('keydown', (e) => {
								if (e.key === 'Enter') {
									e.preventDefault();
									ifEnterPress(this);
								}
							});
							currentElement.focus();
						}
						if (optionLabels.includes("Finalizada")) {
							currentElement.value = "8"; // Seleccionar Finalizada
							currentElement.dispatchEvent(new Event('change'));
							await waitForElement('//*[@id="formulario:final_focus"]');
							await sleep(500);
							currentElement = document.getElementById('formulario:final_focus');
							currentElement.addEventListener('keydown', (e) => {
								if (e.key === 'Enter') {
									e.preventDefault();
									ifEnterPress(this);
								}
							});
							currentElement.focus();
						}
					}
					if (currentElement.options[currentElement.selectedIndex].text == "Visado") {
						let optionLabels = Array.from(currentElement.options).map((opt) => opt.text);
						if (optionLabels.includes("Finalizada")) {
							currentElement.value = "8"; // Seleccionar Finalizada
							currentElement.dispatchEvent(new Event('change'));
							await waitForElement('//*[@id="formulario:final_focus"]');
							await sleep(500);
							currentElement = document.getElementById('formulario:final_focus');
							currentElement.addEventListener('keydown', (e) => {
								if (e.key === 'Enter') {
									e.preventDefault();
									ifEnterPress(this);
								}
							});
							currentElement.focus();
						}
					}
					localStorage.setItem("CurrentHotkey", "");


				} else {
					console.log('Element not found formulario:listaEstados_focus');
				}
			});

			/* FIN HOTKEY 2 */ }

			/* HOTKEY 3 SUBIR DILIGENCIA */ {
			Mousetrap.bindGlobal('alt+d', async function(e) {
				e.preventDefault(); // Prevent default behavior of hotkey

				currentElement = document.getElementById('formulario:listaFicheros_0:tipoDocumento');
				currentElement.value = "23"; // Seleccionar Diligencia
				currentElement.dispatchEvent(new Event('change'));
				currentElement = document.getElementById('formulario:listaFicheros_0:estado');
				currentElement.value = "2"; // Seleccionar Finalizado
				currentElement.dispatchEvent(new Event('change'));
				currentElement = document.getElementById('formulario:listaFicheros_0:notificar');
				currentElement.value = "0"; // Seleccionar No
				currentElement.dispatchEvent(new Event('change'));
				currentElement = document.getElementById('formulario:listaFicheros_0:nombre');
				currentElement.value = "DILIGENCIA";
				currentElement.dispatchEvent(new Event('change'));
				document.getElementById('formulario:listaFicheros_0:visitaValidada').focus();
				currentElement = document.getElementById('formulario:listaFicheros_0:fechaDiligencia');
				currentElement.focus();

			});

			/* FIN HOTKEY 3 */ }

			/* HOTKEY 4 GUARDAR */ {
			Mousetrap.bindGlobal('alt+g', async function(e) {
				e.preventDefault(); // Prevent default behavior of hotkey

				currentElement = document.getElementById('formulario:j_idt960:guardar:control-guardar');
				currentElement.click();
			});

            /* FIN HOTKEY 4 */ }

			/* HOTKEY 5 VISUALIZAR */ {
			Mousetrap.bindGlobal('alt+v', async function(e) {
				e.preventDefault(); // Prevent default behavior of hotkey

				currentElement = document.getElementById('formulario:_id35');
				if (currentElement) currentElement.click();
                currentElement = document.getElementById('formulario:j_idt960:imprimirLink_2:control-imprimirLink_2');
				if (currentElement) currentElement.click();
			});

			/* FIN HOTKEY 5 */}

            /* HOTKEY 6 ABRIR ENLACES EN NUEVA PESTAÑA */ {
			Mousetrap.bindGlobal('alt+n', async function(e) {
				e.preventDefault(); // Prevent default behavior of hotkey

                if (!document.getElementById('divNewTab')) {
                    const divNewTab = document.createElement('div');
                    divNewTab.id = 'divNewTab';
                    divNewTab.textContent = '';
                    divNewTab.style.color = 'red';
                    divNewTab.style.fontWeight = 'bold';
                    document.body.appendChild(divNewTab);
                }
                else {
                    const divNewTab = document.getElementById('divNewTab');

                }

                if (document.getElementById('formulario').target == '') {
                    document.getElementById('formulario').target = '_blank';
                    divNewTab.textContent = 'ABRIR EN PESTAÑA NUEVA';
                }
                else {
                    document.getElementById('formulario').target = '';
                    divNewTab.textContent = '';
                }
			});

			/* FIN HOTKEY 6 */ }
		};
		document.head.appendChild(pluginGlobalBind);
    }
    document.head.appendChild(scriptHotkeys);

    //////////////////////////////////////////////////////////
    //
    //             FIN
    //    Definicion de hotkeys
    //
    /*//////////////////////////////////////////////////////*/ }

    //////////////////////////////////////////////////////////
    //
    //             INICIO
    //    Arreglar campo codigo del formulario de consulta
    //    Para que ponga automaticamente 36/ al principio,
    //    añada ceros a la izquierda y ponga el año actual
    //    si no se especifica
    //
    /*//////////////////////////////////////////////////////*/ {

    function fixCampoOrdenServicio(campo) {
        var trozos = campo.value.split ("/");
        var fecha = new Date();
        if (trozos[0] != null && trozos[1] != null && trozos[1] != ""){
            while (trozos[1].length < 7){
                trozos[1] = "0"+trozos[1];
            }
            if (trozos[2] == null){
                trozos[2] = (fecha.getFullYear()).toString();
                trozos[2] = trozos[2].substring(2,4);
            }
            if(trozos[2].length<2){
                trozos[2] = "0"+trozos[2];
            }
            campo.value = trozos[0]+"/"+trozos[1]+"/"+trozos[2];
        }
    }

    function ifEnter(campo) {
        if (window.event && window.event.keyCode == 13) {
            fixCampoOrdenServicio(campo);
            busquedaAvanzada();
        }
    }

    const scriptFormularioConsulta = document.createElement('script');
    scriptFormularioConsulta.type = 'text/javascript';
    scriptFormularioConsulta.textContent = fixCampoOrdenServicio.toString();
    scriptFormularioConsulta.textContent = scriptFormularioConsulta.textContent + '\n' + ifEnter.toString();
    currentElement = document.getElementById('formulario:strOrdenServicio');
    if (currentElement) {
        currentElement.value = "36/";
        currentElement.setAttribute("onblur", 'javascript:fixCampoOrdenServicio(this)');
        currentElement.setAttribute("onkeypress", 'javascript:ifEnter(this);');
    }
    document.head.appendChild(scriptFormularioConsulta);

    //////////////////////////////////////////////////////////
    //
    //             FIN
    //    Arreglar campo codigo del formulario de consulta
    //
    /*//////////////////////////////////////////////////////*/ }

    //////////////////////////////////////////////////////////
    //
    //             INICIO
    //    Resaltar campos incorrectos en oficio
    //
    /*//////////////////////////////////////////////////////*/ {
    function resaltarCampo(campo,texto) {
        currentElement = document.getElementById(campo);
        if (currentElement) {
            if (currentElement.tagName == "INPUT") {
                if (currentElement.value == texto) {
                    currentElement.style.backgroundColor = 'red';
                    currentElement.style.color = 'white';
                }
            }
            if (currentElement.tagName == "SELECT") {
                var selectedText = currentElement.options[currentElement.selectedIndex].text;
                if (selectedText == texto) {
                    currentElement.style.backgroundColor = 'red';
                    currentElement.style.color = 'white';
                }
            }
        }
    }

    // Obtener tipo de destinatario
    var selectedText = '';
    currentElement = document.getElementById('formulario:cbDestinatarioCMB');
    if (currentElement) {
        selectedText = currentElement.options[currentElement.selectedIndex].text;
    }
    currentElement = document.getElementById('formulario:cbDestinatario_input');
    if (currentElement) {
        selectedText = currentElement.value;
    }
    if (selectedText != '') {
        // Si el informe NO es interno
        if (selectedText != "Jefe de Unidad Especializada de Seguridad y Salud" && selectedText != "Jefe de la Unidad Especializada de Lucha contra el Fraude" && selectedText != "Jefatura inspeccion provincial") {
            resaltarCampo('formulario:sReferencia','');
            resaltarCampo('formulario:asunto','');
            resaltarCampo('formulario:fechaInforme','');
            resaltarCampo('formulario:cbFirmaCMB','Oficio sin ventanilla');
            resaltarCampo('formulario:cbFirmaCMBV','Oficio sin ventanilla');
            resaltarCampo('formulario:direccionDest','');
            resaltarCampo('formulario:codPostalDest','');
            resaltarCampo('formulario:codProvinciaDestCMB','');
            resaltarCampo('formulario:codMunicipioDestCMB','');
            resaltarCampo('formulario:comboNotificarCMB','No');

            // Comprobar que el destinatario no lleve el numero de DNI
            currentElement = document.getElementById('formulario:destinatario');
            if (currentElement.value.match(/[^\d]*\d+[^\d]*/)) {
                currentElement.style.backgroundColor = 'red';
                currentElement.style.color = 'white';
            }
        }
    }

    //////////////////////////////////////////////////////////
    //
    //             FIN
    //    Resaltar campos incorrectos en oficio
    //
    /*//////////////////////////////////////////////////////*/ }

    //////////////////////////////////////////////////////////
    //
    //             INICIO
    //    Poner titulo a las pestañas que no lo tienen
    //
    /*//////////////////////////////////////////////////////*/ {
    if (document.title == '') {
        if (window.location.href.indexOf('portalitss.meyss.es/registroDocs/detalle/DetalleAsientosEntrada.faces') > -1) {
            document.title = 'Registro';
        }
        if (window.location.href.indexOf('portalitss.meyss.es/integra/accioninspectora/OrdenServicioDatosGenerales.faces') > -1) {
            document.title = 'Datos Generales';
        }
    }


    //////////////////////////////////////////////////////////
    //
    //             FIN
    //    Poner titulo a las pestañas que no lo tienen
    //
    /*//////////////////////////////////////////////////////*/ }
})();